import socket
import threading

def func(new_socket, new_address):
    print(f"{str(new_address)}上线了")
    recv_data = new_socket.recv(1024)
    if not recv_data:
        print(f"{str(new_address)}已下线")
        new_socket.close()
        return
    data = recv_data.decode().split(" ")[1]
    print(data)
    print(data)
    if data == "/":
        data = "/index.html"
    try:
        with open("baoke" + data,"rb") as file:
            file_data = file.read()

    except:
        with open("baoke/404.html","rb") as file:
            file_data = file.read()
        html_data = "HTTP/1.1 404 NotFind\r\nServer: PWS\r\n\r\n".encode() + file_data
    else:
        html_data = "HTTP/1.1 200 OK\r\nServer: PWS\r\n\r\n".encode() + file_data
    finally:
        new_socket.send(html_data)
        new_socket.close()




def main():
    tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcp_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    tcp_socket.bind(("",8080))
    tcp_socket.listen(128)
    while True:
        new_socket, new_address= tcp_socket.accept()
        threading.Thread(target=func, args=(new_socket, new_address),daemon=True).start()

if __name__ == '__main__':
    main()